/*
	MIDAS Context Based Routing
	cbr_rtable.cc
	Copyright (c) 2007 Radoslaw Olgierd Schoeneich
	MEAG IT PW
*/

#include <utility>
#include "cbr_rtable.h"

/**
 * @todo:
 * - cbr_RTable needs a rename badly
 */

/**
 * Add new CBR transaction to CBR transactions table.
 *
 * @param trID transaction ID
 * @param dst CBR id of the destination node
 * @param fwdr CBR id of the forwarding node
 */

void cbr_RTable::insert(u_int32_t trID, cbr_ID dst, cbr_ID fwdr)
{
	routes_list::iterator i;

	for (i = routes.begin(); i != routes.end(); i++) {
		if (i->trID == trID && i->dst == dst)
			break;
	}
	if (i != routes.end()) {
		// FIXME: is this OK?
		i->forwarder = fwdr;
	} else {
		routes.push_front(entry(trID, dst, fwdr));
	}
}

/**
 * Remove CBR transaction from CBR transactions table.
 *
 * @param trID transaction ID
 * @param dst CBR id of the destination node
 */

void cbr_RTable::remove(u_int32_t trID, cbr_ID dst)
{
	routes_list::iterator i;

	for (i = routes.begin(); i != routes.end(); i++) {
		if (i->trID == trID && i->dst == dst) {
			routes.erase(i);
			return;
		}
	}
}

/**
 * Lookup for the CBR id of the forwarding node given CBR transaction data.
 *
 * @param trID transaction ID
 * @param dst CBR id of the destination node
 * @param fwdr pointer to store CBR id of the forwarding node
 *
 * @return "true" if given CBR transaction exists, "false" otherwise.
 */

bool cbr_RTable::getForwarderID(u_int32_t trID, cbr_ID dst, cbr_ID *fwdr)
{
	routes_list::const_iterator i;

	for (i = routes.begin(); i != routes.end(); i++) {
		if (i->trID == trID && i->dst == dst) {
			if (fwdr)
				*fwdr = i->forwarder;
			return true;
		}
	}

	return false;
}
